<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="tree-card">
        <tree-tools
          :tree-node="company"
          :is-root="true"
          @editDeps="editDeps"
          @adddepts="adddepts"
        ></tree-tools>

        <!-- 树形结构 -->
        <el-tree
          :data="departs"
          :props="defaultProps"
          :default-expand-all="true"
          :expand-on-click-node="false"
        >
          <!-- 树形结构 -->
          <template v-slot="{data}">
            <tree-tools
              :tree-node="data"
              style="width: 100%"
              @adddepts="adddepts"
              @delbumen="getDepartmentTrees"
              @editDeps="editDeps"
            ></tree-tools>
          </template>
        </el-tree>
      </el-card>

      <!-- 弹层组件 -->
      <!-- 方式1  使用v-if创建和销毁组件 并且实现表单清空 非常实用最好! -->
      <add-depts ref="addDepsRef" :show-add-dlog.sync="showAddDlog" :tree-node="node" @addDepartment="getDepartmentTrees"></add-depts>
    </div>
  </div>
</template>

<script>
import TreeTools from './compontes/tree-tools'
import AddDepts from './compontes/add-depts'
import { getDepartmentTree } from '@/api/departments'
import { transListToTreeData } from '@/utils/index'
export default {
  name: 'Departments',
  components: {
    TreeTools,
    AddDepts
  },
  props: {},
  data() {
    return {
      company: {},
      departs: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      showAddDlog: false, // 是否显示弹出层
      node: {} // 当前选中的节点
    }
  },
  created() {
    this.getDepartmentTrees()
  },
  mounted() {},
  methods: {
    async getDepartmentTrees() {
      const data = await getDepartmentTree()
      // 方式1 利用双重for循环
      data.depts.forEach(t => {
        // 查找子部门
        const children = data.depts.filter(i =>
          i.pid === t.id)
        if (children && children.length > 0) {
          t.children = children
        }
      })
      this.company = { name: data.companyName, manager: data.companyManage || '负责人', id: '' } // 手动传入id为'' 这是因为第一级结构没有id属性,而第二级结构的pid为''
      // 方式2 利用递归
      this.departs = transListToTreeData(data.depts)
    },
    // 添加部门事件
    adddepts(node) {
      this.showAddDlog = true
      this.node = node
      console.log(this.node)
    },
    // 编辑部门事件
    async editDeps(node) {
      // console.log(node)
      this.showAddDlog = true
      this.node = node
      // 请求当前节点数据
      // const fromData = await getDepartDateilById(this.node.id)
      // console.log(fromData)
      // 方式1 直接修改子组件的数据
      // this.$refs.addDepsRef.formData = fromData
      // 方式2 通过访问子组件调用子组件的请求数据方法
      this.$refs.addDepsRef.getDepartDateilById(this.node.id)
    }

  }
}
</script>

<style lang="scss" scoped>
.tree-card {
  padding: 30px 140px;
  font-size: 14px;
}

.el-dropdown-link {
  cursor: pointer;
}
</style>
